package com.lagou.edu.context;

import com.lagou.edu.context.annotation.*;
import com.lagou.edu.utils.Assert;
import com.lagou.edu.utils.ScanningFile;
import com.lagou.edu.utils.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * 上下文监听器
 *
 * @author bwcx_jzy
 * @since 2021/10/21
 */
public class ContextLoaderListener implements ServletContextListener {

    private DefaultBeanFactory defaultBeanFactory;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        String configClass = servletContext.getInitParameter("configClass");
        Assert.hasLength(configClass, "请配置 context-param -> configClass");
        //
        defaultBeanFactory = new DefaultBeanFactory();
        //
        Class<?> classForName = StringUtils.classForName(configClass);
        try {
            this.initClassInfo(classForName);
            this.loadClassInfo(classForName);
        } catch (Exception e) {
            throw new RuntimeException("加载配置错误:" + classForName.getName(), e);
        }
        //
        String[] componentScan = this.convertComponentScan(classForName);
        List<Class<?>> allClass = new ArrayList<>();
        ScanningFile scanningFile = new ScanningFile();
        for (String itemName : componentScan) {
            scanningFile.addPackage(itemName);
        }
        scanningFile.setFilter(aClass -> {
            // System.out.println(aClass);
            return aClass.isAnnotationPresent(Service.class) || aClass.isAnnotationPresent(Repository.class);
        });
        scanningFile.setListener(allClass::add);
        scanningFile.scan();
        //
        Class<?> nowClass = Void.class;
        try {
            for (Class<?> aClass : allClass) {
                nowClass = aClass;
                this.initClassInfo(aClass);
            }
            for (Class<?> aClass : allClass) {
                nowClass = aClass;
                this.loadClassInfo(aClass);
            }
        } catch (Exception e) {
            throw new RuntimeException("加载配置错误:" + nowClass.getName(), e);
        }
        //
        ApplicationContextUtil.setBeanFactory(defaultBeanFactory);
    }

    /**
     * 初始化 class 信息
     *
     * @param cls class
     * @throws Exception 异常
     */
    private void initClassInfo(Class<?> cls) throws Exception {
        // 加载配置文件
        this.loadClassImportProperties(cls);
        // 创建 bean 对象
        this.initBean(cls);
    }

    /**
     * 加载 class bean 的信息
     *
     * @param cls class
     * @throws IllegalAccessException    异常
     * @throws InvocationTargetException 异常
     */
    private void loadClassInfo(Class<?> cls) throws IllegalAccessException, InvocationTargetException {
        //
        Object bean = defaultBeanFactory.getObject(cls);
        // 加载属性
        Object originalObject = defaultBeanFactory.getOriginalObject(cls);
        this.loadBeanFieldValue(cls, originalObject);
        //
        this.loadMethodBean(cls, bean);
        //
        this.loadBeanFieldAutowired(cls, originalObject);
    }

    /**
     * 初始化创建 bean 对象
     *
     * @param cls class
     * @throws Exception 异常
     */
    private void initBean(Class<?> cls) throws Exception {
        // 创建对象
        Object o = cls.getDeclaredConstructor().newInstance();
        Object proxyObject = defaultBeanFactory.getProxyFactory().createProxyObject(o);

        BeanData beanData = new BeanData(o, proxyObject);
        String beanName = this.convertBeanName(cls);
        defaultBeanFactory.regBean(beanName, cls, beanData);
        // 注册多接口 bean
        Class<?>[] interfaces = cls.getInterfaces();
        for (Class<?> anInterface : interfaces) {
            defaultBeanFactory.regClassBeanName(beanName, anInterface);
        }
    }


    /**
     * 转换 bean 名称
     *
     * @param cls class
     * @return 名称，没有配置为 class name 首字母小写
     */
    private String convertBeanName(Class<?> cls) {
        String customName = "";
        Repository repository = cls.getAnnotation(Repository.class);
        Service service = cls.getAnnotation(Service.class);
        if (repository != null) {
            customName = repository.value();
        } else if (service != null) {
            customName = service.value();
        }
        if (customName.isEmpty() || customName.isBlank()) {
            String simpleName = cls.getSimpleName();
            return simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
        }
        return customName;
    }

    /**
     * 加载配置文件
     *
     * @param cls class
     */
    private void loadClassImportProperties(Class<?> cls) throws IOException {
        Import annotation = cls.getAnnotation(Import.class);
        if (annotation == null) {
            return;
        }
        String[] value = annotation.value();
        if (value == null || value.length <= 0) {
            return;
        }
        for (String item : value) {
            InputStream resourceAsStream = ContextLoaderListener.class.getResourceAsStream(item);
            Assert.notNull(resourceAsStream, "没有加载到对应到配置文件：" + item);
            defaultBeanFactory.loadProperties(resourceAsStream);
        }
    }

    /**
     * 加载 bean 中属性值
     *
     * @param cls    class
     * @param object 对象
     * @throws IllegalAccessException 异常
     */
    private void loadBeanFieldValue(Class<?> cls, Object object) throws IllegalAccessException {
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            this.loadBeanFieldValue(declaredField, object);
        }
    }

    /**
     * 加载  属性值
     *
     * @param field  属性
     * @param object 对象
     * @throws IllegalAccessException 异常
     */
    private void loadBeanFieldValue(Field field, Object object) throws IllegalAccessException {
        Value annotation = field.getAnnotation(Value.class);
        if (annotation == null) {
            return;
        }
        String value = annotation.value();
        String properties = defaultBeanFactory.getProperties(value);
        field.setAccessible(true);
        field.set(object, properties);
    }


    /**
     * 加载 class 属性注入对象
     *
     * @param cls    class
     * @param object bean 对象
     * @throws IllegalAccessException 权限异常
     */
    private void loadBeanFieldAutowired(Class<?> cls, Object object) throws IllegalAccessException {
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            this.loadBeanFieldAutowired(declaredField, object);
        }
    }

    /**
     * 加载属性注入对象
     *
     * @param field  属性
     * @param object bean 对象
     * @throws IllegalAccessException 权限异常
     */
    private void loadBeanFieldAutowired(Field field, Object object) throws IllegalAccessException {
        Autowired annotation = field.getAnnotation(Autowired.class);
        if (annotation == null) {
            return;
        }
        String value = annotation.value();
        Object beanObject = value.isBlank() ? defaultBeanFactory.getObject(field.getType()) : defaultBeanFactory.getObject(value);
        field.setAccessible(true);
        field.set(object, beanObject);
    }

    /**
     * 加载 class 中 方法中的 bean
     *
     * @param cls    class
     * @param object 对象
     * @throws InvocationTargetException 异常1
     * @throws IllegalAccessException    异常2
     */
    private void loadMethodBean(Class<?> cls, Object object) throws InvocationTargetException, IllegalAccessException {
        Method[] declaredMethods = cls.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            Bean annotation = declaredMethod.getAnnotation(Bean.class);
            if (annotation == null || !Modifier.isPublic(declaredMethod.getModifiers())) {
                continue;
            }
            String customName = annotation.value();
            String declaredMethodName = declaredMethod.getName();
            if (customName.isBlank()) {
                customName = declaredMethodName.substring(0, 1).toLowerCase() + declaredMethodName.substring(1);
            }
            Object invoke = declaredMethod.invoke(object);
            BeanData beanData = new BeanData(invoke, invoke);
            defaultBeanFactory.regBean(customName, declaredMethod.getReturnType(), beanData);
        }
    }

    /**
     * 转换 需要扫描的包
     *
     * @param classForName 配置的class
     * @return 可以扫描的包
     */
    private String[] convertComponentScan(Class<?> classForName) {
        ComponentScan annotation = classForName.getAnnotation(ComponentScan.class);
        if (annotation == null) {
            String packageName = classForName.getPackageName();
            return new String[]{packageName};
        }
        String[] value = annotation.value();
        if (value == null || value.length <= 0) {
            String packageName = classForName.getPackageName();
            return new String[]{packageName};
        }
        return value;
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
